package com.bawei.module_moto_circle.ui.post.adapter

import android.graphics.Color
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.bawei.lib_common.dp
import com.bawei.lib_common.utils.ToastUtils
import com.bawei.lib_common.widget.nine_pic_grid.Image
import com.bawei.lib_image.GlideApp
import com.bawei.module_moto_circle.databinding.LayoutPostItemBinding
import com.bawei.module_moto_circle.model.PostInfo
import com.bumptech.glide.load.resource.bitmap.RoundedCorners

/**
 *作者：lxy
 *功能:
 *时间：2025/6/2
 */
class PostViewHolder(
    itemView: View,
    val mBinding:LayoutPostItemBinding,
    private val onUserClick: ((PostInfo) -> Unit)? = null,
    private val onItemClick: ((PostInfo, Int) -> Unit)? = null,
    private val onImageClick: ((Int, Int, List<Image>) -> Unit)? = null,
    private val onShareClick: ((PostInfo) -> Unit)? = null,
    private val onCommentsClick: ((PostInfo) -> Unit)? = null,
    private val onLikeClick: ((PostInfo, Int) -> Unit)? = null,
    private val onMoreActionClick: ((PostInfo, Int) -> Unit)? = null,
    private val onLikeViewClick: ((PostInfo, Int, View) -> Unit)? = null,
    private val onCollectionViewClick: ((PostInfo, Int, View) -> Unit)? = null,
    private val onFollowClick: ((PostInfo, Int, View) -> Unit)? = null,
    private val onFollowViewClick: ((PostInfo, Int, View) -> Unit)? = null
) : RecyclerView.ViewHolder(itemView) {

    var postInfo: PostInfo? = null

    var isClickSpan: Boolean = false

    fun setMaxLines(max: Int) {
        mBinding.tvPostContent.maxLines = max
    }
    /**
     * 绑定数据和UI，databinding做不到的，需要自己写
     * 九宫格图片处理
     * 视频处理
     * 话题处理:富文本
     */
    fun initView(postItem:PostInfo,position:Int) {
        this.postInfo = postItem

        mBinding.apply {
            lFollowState.isSelected = postItem.hasFollowed()
            //处理话题
            if (postItem.topics.isNullOrEmpty()) {
                tvPostContent.text = postItem.content
            } else {
                handleTopic(postItem)
            }
            //处理图片或视频
            handlePicOrVideo(postItem)
        }
    }


    private fun handlePicOrVideo(postItem: PostInfo) {
        mBinding.apply {
            if (postItem.image?.size == 1 && postItem.image[0].contentType?.contains("video") == true) {
                lVideo.setOnClickListener {
                    clickItem()
                }
                //设置视频
                val video = postItem.image.firstOrNull() ?: return
                val videoHeight = video.imageHeight
                val videoWidth = video.imageWidth
                if (videoHeight > videoWidth) {
                    lVideo.setPortrait()
                    GlideApp.with(mBinding.root).load(video.url)
                        .override(343.dp,180.dp)
                        .transform(RoundedCorners(4.dp),)
                        .into(ivVideo)

                } else {
                    lVideo.setLandscape()
                    GlideApp.with(mBinding.root).load(video.url)
                        .override(311.dp,233.dp)
                        .transform(RoundedCorners(4.dp),)
                        .into(ivVideo)
                }
                ivPlay.visibility = View.VISIBLE
                //视频
                nineGridView.visibility = View.GONE
                lVideo.visibility = View.VISIBLE
            }else{
                nineGridView.setPicsList(postItem.image!!) //设置图片资源
                nineGridView.initView()
                nineGridView.visibility = View.VISIBLE
                lVideo.visibility = View.GONE
            }
        }


    }

    /**
     * 处理话题：富文本
     */
    private fun handleTopic(postItem: PostInfo) {
        val content = postItem.content
        val spannableStringBuilder = SpannableStringBuilder(content)
        //保存话题的起始位置
        val topicIndexMap = mutableMapOf<String,MutableList<Int>>() //键:话题内容 值:话题开始和结束的位置
        //保存话题的id
        val topicIdMap = mutableMapOf<String,String>()//键:话题内容 值:话题id

        val topics = postItem.topics
        topics?.forEach{
            //话题前后加#
            val topicName = String.format("#%s#",it.topicName)
            //找的内容
            var temp = content

            while (true){
                val start = temp?.indexOf(topicName)
                if(start!! > -1){ //找到了
                    if(topicIndexMap[topicName] == null){
                        topicIndexMap[topicName] = mutableListOf()
                    }
                    topicIndexMap[topicName]?.add(start)
                    topicIndexMap[topicName]?.add(start+topicName.length)
                    topicIdMap[topicName] = it.topicId.toString()
                }else{ //没找到
                    break
                }
                //继续从后面开始找
                temp = temp?.substring(start+topicName.length).toString()
            }
        }
        //今日份车溜子#日常溜车#   #日常溜车#   topicIndexMap:"#日常溜车#":[6,11]    topicIdMap:"#日常溜车#":"1643118469338963969"
        Log.d("handleTopic", "内容: $content")
        Log.d("handleTopic", "起始位置: $topicIndexMap")
        Log.d("handleTopic", "id: $topicIdMap")
        //富文本
        topicIndexMap.forEach{name,list ->
            spannableStringBuilder.setSpan(object : ClickableSpan(){
                override fun onClick(widget: View) {
                    ToastUtils.showLong(itemView.context,"点击了话题id ${topicIdMap[name]}")
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(itemView.context, com.bawei.lib_common.R.color.topic)
                    ds.isUnderlineText = false
                }

            },list[0],list[1], SpannableStringBuilder.SPAN_EXCLUSIVE_INCLUSIVE)
        }
        mBinding.tvPostContent.apply {
            movementMethod = LinkMovementMethod.getInstance()
            highlightColor = Color.TRANSPARENT
            text = spannableStringBuilder

        }
    }



    fun clickItem() {
        if (isClickSpan) {
            isClickSpan = false
            return
        }
        onItemClick?.invoke(mBinding.post!!, this.absoluteAdapterPosition)
    }

    fun clickUser() {
        if (mBinding.post!!.isOfficial()) return
        onUserClick?.invoke(mBinding.post!!)
    }

    fun clickCollection() {
        val post =
            (this.bindingAdapter as PostPagingAdapter).getPostItem(this.absoluteAdapterPosition)!!
        mBinding.placeholder.tag = mBinding.ivCollection
        onCollectionViewClick?.invoke(
            post,
            this.absoluteAdapterPosition,
            mBinding.placeholderCollection
        )
        this.bindingAdapter?.notifyItemChanged(this.absoluteAdapterPosition, "update")
    }

    fun clickFollow() {
//            JLogUtil.http("clickFollow called with onFollowClick = $onFollowClick")
        onFollowClick?.invoke(
            mBinding.post!!,
            this.absoluteAdapterPosition,
            mBinding.lFollowState
        )
    }

    fun clickComments() {
        onCommentsClick?.invoke(mBinding.post!!)
    }

    fun clickShare() {
        onShareClick?.invoke(mBinding.post!!)
    }

    fun clickMoreAction() {
        onMoreActionClick?.invoke(mBinding.post!!, this.absoluteAdapterPosition)
    }

    fun clickLike() {
        onLikeClick?.invoke(postInfo!!,this.absoluteAdapterPosition)
        onLikeViewClick?.invoke(postInfo!!, this.absoluteAdapterPosition,mBinding.placeholder)
    }
}

fun View.setLandscape() {
    val l = layoutParams
    l.width = 343.dp
    l.height = 180.dp
    layoutParams = l
}

fun View.setPortrait() {
    val l = layoutParams
    l.width = 233.dp
    l.height = 311.dp
    layoutParams = l
}